package com.sqx.modules.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.goods.dao.GoodsDao;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.sign.dao.GoldRecordsDao;
import com.sqx.modules.sign.dao.TbSigninDao;
import com.sqx.modules.sign.entity.GoldRecords;
import com.sqx.modules.sign.entity.TbSignin;
import com.sqx.modules.task.dao.TbDailyTasksDao;
import com.sqx.modules.task.dao.TbUserTaskDao;
import com.sqx.modules.task.entity.TbDailyTasks;
import com.sqx.modules.task.entity.TbUserTask;
import com.sqx.modules.task.service.TbUserTaskService;
import com.sqx.modules.tbOrders.dao.TbOrdersDao;
import com.sqx.modules.tbOrders.entity.TbOrders;
import com.sqx.modules.userCertification.dao.UserCertificationDao;
import com.sqx.modules.userCertification.entity.UserCertification;
import com.sqx.modules.userCertification.service.UserCertificationService;
import com.sun.corba.se.spi.ior.IdentifiableFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Admin
 * @description 针对表【tb_user_task(用户每日任务完成情况表)】的数据库操作Service实现
 * @createDate 2024-07-22 10:56:35
 */
@Service
public class TbUserTaskServiceImpl extends ServiceImpl<TbUserTaskDao, TbUserTask>
        implements TbUserTaskService {

    @Autowired
    private TbDailyTasksDao tbDailyTasksDao;

    @Autowired
    private UserCertificationDao userCertificationDao;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private TbOrdersDao tbOrdersDao;

    @Autowired
    private GoldRecordsDao goldRecordsDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TbSigninDao tbSigninDao;


    @Override
    public Result getTbUserTaskList(Integer pageNum, Integer pageSize, TbUserTask tbUserTask) {
        PageHelper.startPage(pageNum, pageSize);
        LocalDate startTime = LocalDate.now();
        List<TbDailyTasks> dailyTasksList = tbDailyTasksDao.selectList(null);
        if (dailyTasksList != null) {
            for (TbDailyTasks tbDailyTasks : dailyTasksList) {
                boolean isCompleted = false;
                // 如果是一次性任务
                if (tbDailyTasks.getOneMission() == 1) {
                    TbUserTask tbUserTask1 = baseMapper.selectByTaskId(tbUserTask.getUserId(), tbDailyTasks.getId());
                    isCompleted = tbUserTask1 != null && tbUserTask1.getState() == 1;
                } else {
                    List<TbUserTask> tbUserTask1 = baseMapper.selectByCreateTime(tbUserTask.getUserId(), startTime, tbDailyTasks.getId());
                    for (TbUserTask task : tbUserTask1) {
                        if (task.getState() == 1) {
                            isCompleted = true;
                            break;
                        }
                    }
//                    isCompleted = tbUserTask1 != null && tbUserTask1.getState() == 1;
                }
                if (isCompleted) {
                    // 只有在任务完成时调用奖励领取逻辑
                    claimReward(tbUserTask.getUserId(), tbDailyTasks);
                    tbDailyTasks.setComplete(true); // 设置任务为已完成
                } else {
                    tbDailyTasks.setComplete(false);
                }
            }
            // 获取用户认证信息
            UserCertification userCertification = userCertificationDao.selectOne(new QueryWrapper<UserCertification>().eq("user_id", tbUserTask.getUserId()));
            if (userCertification != null && userCertification.getStatus() == 1) {
                // 获取实名任务
                TbDailyTasks realNameAuthTask = tbDailyTasksDao.selectOne(new QueryWrapper<TbDailyTasks>().eq("task_type", "REAL_NAME_AUTH"));
                if (realNameAuthTask != null) {
                    // 检查用户是否已经有对应的实名任务记录
                    TbUserTask existingTask = baseMapper.selectByTaskId(userCertification.getUserId(), realNameAuthTask.getId());
                    if (existingTask == null) {
                        // 添加新的实名任务记录
                        TbUserTask newTask = new TbUserTask();
                        newTask.setTaskId(realNameAuthTask.getId());
                        newTask.setUserId(tbUserTask.getUserId());
                        newTask.setRewardClaimed(1);
                        newTask.setState(1);
                        newTask.setCreateTime(new Date());
                        int result = baseMapper.insert(newTask);
                        if (result > 0) {
                            realNameAuthTask.setComplete(true); // 设置任务为已完成
                        }
                    }
                }
            }
            return Result.success().put("data", new PageInfo<>(dailyTasksList));
        }
        return Result.error("暂无任务，请先添加任务");
    }

    @Override
    public Result selectTbOrders(Long userId, Long taskId) {
        List<TbOrders> tbOrders = tbOrdersDao.selectBySellerId(userId);
        if (!tbOrders.isEmpty()){
            TbOrders tbOrders1 = tbOrders.get(0);
            tbOrders1.setTaskId(taskId);
            tbOrdersDao.updateById(tbOrders1);
            TbUserTask tbUserTask = new TbUserTask();
            tbUserTask.setUserId(userId);
            tbUserTask.setTaskId(tbOrders1.getTaskId());
            tbUserTask.setState(1);
            tbUserTask.setRewardClaimed(0);
            baseMapper.insert(tbUserTask);
        }
        return Result.success();
    }

    @Override
    public Result selectAllList(Integer pageNum, Integer pageSize, TbDailyTasks tbDailyTasks) {
        PageHelper.startPage(pageNum, pageSize);
        List<TbDailyTasks> dailyTasksList = tbDailyTasksDao.selectList(null);
        return Result.success().put("data", new PageInfo<>(dailyTasksList));
    }

    private void claimReward(Long userId, TbDailyTasks tbDailyTasks) {
        // 查询用户任务状态
        List<TbUserTask> tbUserTask = baseMapper.selectList(new QueryWrapper<TbUserTask>().eq("user_id",userId)
                .eq("task_id",tbDailyTasks.getId()));
        if (tbUserTask == null || tbUserTask.isEmpty()) {
            return;
        }
        for (TbUserTask task : tbUserTask) {
           if (task.getRewardClaimed() == 1){
               continue;
           }
            // 更新TbUserTask表中的rewardClaimed字段
            task.setRewardClaimed(1);
            baseMapper.updateById(task);
            // 根据任务类型执行相应的奖励逻辑
            String taskType = tbDailyTasks.getTaskType();
            if ("REAL_NAME_AUTH".equals(taskType)) {
                handleRealNameAuthReward(userId, tbDailyTasks);
            } else if ("INVITATION_FRIENDS".equals(taskType)) {
                handleInvitationFriendsReward(userId, tbDailyTasks);
            } else if ("PRODUCT_POSTING".equals(taskType)) {
                handleProductPostingReward(userId, tbDailyTasks);
            } else if ("PRODUCT_TRANSACTION".equals(taskType)) {
                handleProductTransactionReward(userId, tbDailyTasks);
            }
        }
        // 验证奖励是否已经被领取
//        if (tbUserTask.getRewardClaimed() == 1) {
//            // 奖励已经领取过，退出方法
//            return;
//        }
        // 更新TbUserTask表中的rewardClaimed字段
//        tbUserTask.setRewardClaimed(1);
//        baseMapper.updateById(tbUserTask);

    }

    private void handleProductTransactionReward(Long userId, TbDailyTasks tbDailyTasks) {
        TbOrders tbOrders = tbOrdersDao.selectByUserId(userId, tbDailyTasks.getId());
        if (tbOrders != null) {
            GoldRecords records = new GoldRecords();
            records.setUserId(userId);
            records.setGoldChange(1);
            records.setRemark("商品交易奖励");
            records.setCreateTime(new Date());
            records.setRelatedId(tbOrders.getOrderId());
            records.setGoldCoins(tbDailyTasks.getSpecies());
            goldRecordsDao.insert(records);
            UserEntity user = userDao.selectById(userId);
            user.setTotalGold(user.getTotalGold() + tbDailyTasks.getSpecies());
            userDao.updateById(user);
        }
    }

    private void handleProductPostingReward(Long userId, TbDailyTasks tbDailyTasks) {
        Goods goods = goodsDao.selectByUserId(userId, tbDailyTasks.getId());
        if (goods != null) {
            GoldRecords records = new GoldRecords();
            records.setUserId(userId);
            records.setGoldChange(1);
            records.setRemark("商品发布奖励");
            records.setCreateTime(new Date());
            records.setRelatedId(goods.getGoodId());
            records.setGoldCoins(tbDailyTasks.getSpecies());
            goldRecordsDao.insert(records);
            UserEntity user = userDao.selectById(userId);
            user.setTotalGold(user.getTotalGold() + tbDailyTasks.getSpecies());
            userDao.updateById(user);
        }
    }

    private void handleInvitationFriendsReward(Long userId, TbDailyTasks tbDailyTasks) {
        TbSignin signin = tbSigninDao.selectByUserId(userId, tbDailyTasks.getId());
        if (signin != null) {
            GoldRecords records = new GoldRecords();
            records.setUserId(userId);
            records.setGoldChange(1);
            records.setRemark("邀请好友签到奖励");
            records.setCreateTime(new Date());
            records.setRelatedId(signin.getId());
            records.setGoldCoins(tbDailyTasks.getSpecies());
            goldRecordsDao.insert(records);
            UserEntity user = userDao.selectById(userId);
            user.setTotalGold(user.getTotalGold() + tbDailyTasks.getSpecies());
            userDao.updateById(user);
        }
    }

    private void handleRealNameAuthReward(Long userId, TbDailyTasks tbDailyTasks) {
        UserCertification userCertification = userCertificationDao.selectByUserId(userId, tbDailyTasks.getId());
        if (userCertification != null) {
            GoldRecords records = new GoldRecords();
            records.setUserId(userId);
            records.setGoldChange(1);
            records.setRemark("实名认证奖励");
            records.setCreateTime(new Date());
            records.setRelatedId(userCertification.getId());
            records.setGoldCoins(tbDailyTasks.getSpecies());
            goldRecordsDao.insert(records);
            UserEntity user = userDao.selectById(userId);
            user.setTotalGold(user.getTotalGold() + tbDailyTasks.getSpecies());
            userDao.updateById(user);
        }
    }

    /**
     * 每日任务重置
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void resetDailyTasks() {
        // 查询所有每日任务
        List<TbDailyTasks> dailyTasks = tbDailyTasksDao.findAllDailyTasks();
        List<TbUserTask> userTaskList = new ArrayList<>();
        if (dailyTasks != null) {
            for (TbDailyTasks task : dailyTasks) {
                if (task.getOneMission() == null){
                    task.setOneMission(0);
                }
                if (task.getOneMission() != 1) {
                    // 查询所有用户今日完成的每日任务
                    List<TbUserTask> userTasks = baseMapper.findTasksByDateAndType(LocalDate.now(), task.getId());
                    userTaskList.addAll(userTasks);
                }
            }
            if (!userTaskList.isEmpty()) {
                for (TbUserTask userTask : userTaskList) {
                    userTask.setState(0);
                    userTask.setRewardClaimed(0);
                    userTask.setCreateTime(null);
                }
                baseMapper.updateByBatch(userTaskList);
            }
        }
    }
}




